package io.seata.samples.integration.order.dubbo;

import io.seata.samples.integration.common.dto.OrderDTO;
import io.seata.samples.integration.common.response.ObjectResponse;
import io.seata.samples.integration.order.service.ITOrderService;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;
import io.seata.samples.integration.common.order.*;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @Author: heshouyou
 * @Description
 * @Date Created in 2019-09-04
 */

@GrpcService
@Slf4j
@Service
public class OrderDubboServiceImpl extends GreeterGrpc.GreeterImplBase {

    @Autowired
    private ITOrderService orderService;

    @Override
    public void createOrder(OrderRequest request,
                            io.grpc.stub.StreamObserver<OrderResponse> responseObserver) {
//        log.info("全局事务id ：" + RootContext.getXID());
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderNo(request.getOrderNo());
        orderDTO.setOrderAmount(new BigDecimal(request.getOrderAmount()));
        orderDTO.setOrderCount(request.getOrderCount());
        orderDTO.setUserId(request.getUserId());
        ObjectResponse<OrderDTO> order = orderService.createOrder(orderDTO);

        OrderResponse response = OrderResponse.newBuilder()
                .setStatus(order.getStatus())
                .setMessage(order.getMessage())
                .build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public void getOrdersSum(com.google.protobuf.Empty request,
        io.grpc.stub.StreamObserver<OrderSummaryResponse> responseObserver)  {

        Map<String,Object> data = (Map<String, Object>) orderService.getOrderSum().getData();
        OrderSummaryResponse build = OrderSummaryResponse.newBuilder()
                .setLeft((Double) data.get("left"))
                .setTotal((Integer) data.get("total"))
                .build();

        responseObserver.onNext(build);
        responseObserver.onCompleted();
    }
}
